package com.example.ui.contact.adapter;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.NetContact;
import com.example.service.MainService;
import com.example.ui.contact.bean.RequestItem;
import com.example.ui.contact.bean.User;
import com.example.ui.contact.chat.L;
import com.example.ui.contact.chat.SharePreferenceUtil;
import com.example.ui.leftmenu.Item08View;
import com.example.util.BitmapLoad;
import com.example.util.Util;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;


/**
 * 好友请求的列表适配器
 * @author leone.xia
 *
 */
public class FdListViewAdapter extends BaseAdapter {// implements OnClickListener
	private int[] FdimgArr = {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
			R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
			R.drawable.ic_launcher};
	private LayoutInflater inflater;
	private List<String> items;
	private Context mContext ;
	private TextView titleText;
	private List<RequestItem> fd_msgList = new ArrayList<RequestItem>();// 好友请求消息对象数组
	private RequestItem request;
	public static final int RIGHT_CONST = 0; //按下对按钮消息处理
	public static final int ERROR_CONST = 1; //按下错按钮消息处理
	
	public Holder_fd holder = null;
	
	private int curIndex ;
	private RequestItem curItem;

	public FdListViewAdapter(Context mContext,TextView titleText,List<RequestItem> fd_msgList){
		this.mContext = mContext;
		this.titleText = titleText;
		this.fd_msgList = fd_msgList;
		
		inflater = LayoutInflater.from(mContext);
	}

	@Override
	public int getCount() {
		return fd_msgList.size();  //
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}


	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		convertView=null;
		if(convertView == null){
			convertView = inflater.inflate(R.layout.item07_tab2_listview_item, null);
			holder = new Holder_fd();
        	holder.head = (ImageView)convertView.findViewById(R.id.item_list_img);
			holder.text = (TextView) convertView.findViewById(R.id.item_list_text_title);
			holder.right = (Button)convertView.findViewById(R.id.yesId);
			holder.error = (Button)convertView.findViewById(R.id.noId);

			
        	convertView.setTag(holder);
        } else {
            holder = (Holder_fd) convertView.getTag();
        }
		titleText.setText("好友请求");
		//holder.head.setBackgroundResource(FdimgArr[position]);
		//holder.text.setText(FdText[position]);
		
		//		Bitmap bit = null;
		//		String imgUrl =fd_msgList.get(position).getPic() ;
		String name = fd_msgList.get(position).getNick();
		if(name.equals("")){
			name = "Leone";
		}
				
		//		if(imgUrl!=null){
		//			bit=BitmapLoad.loadBitmap(mContext,imgUrl);
		//			@SuppressWarnings("deprecation")
		//			Drawable dra = new BitmapDrawable(bit);
		//			holder.head.setBackgroundDrawable(dra);
		//		}else{
		//			Util.toast(mContext, "网络连接有误，请重试");
		//			holder.head.setBackgroundResource(R.drawable.wall_bg);
		//		}
		
		//curIndex = position;
		holder.text.setText(name);
	//		holder.right.setOnClickListener(fd_msgList.get(position));
	//		holder.error.setOnClickListener(fd_msgList.get(position));
        holder.right.setBackgroundResource(fd_msgList.get(position).getRight_btn_r());
        holder.error.setBackgroundResource(fd_msgList.get(position).getError_btn_r());
		holder.error.setVisibility(fd_msgList.get(position).getError_type());                                    
		holder.right.setVisibility(fd_msgList.get(position).getError_type());
		
        L.showShort(mContext, "position="+position);
        
		        holder.right.setOnClickListener(new View.OnClickListener() {
		
					@Override
					public void onClick(View v) {
						curIndex = position;
						AddRequest();
						Util.toast(mContext, "holder right onclick"+curIndex);
						fd_msgList.get(curIndex).setRight_type(View.INVISIBLE);                                    
						fd_msgList.get(curIndex).setError_type(View.INVISIBLE);
						holder.error.setVisibility(fd_msgList.get(position).getRight_type());                                    
						holder.right.setVisibility(fd_msgList.get(position).getError_type());
						notifyDataSetChanged();
					}
		        	
		        });
		        
		        holder.error.setOnClickListener(new View.OnClickListener() {
		
					@Override
					public void onClick(View v) {
						Util.toast(mContext, "holder error onclick"+curIndex);
						curIndex = position;
						fd_msgList.get(curIndex).setRight_type(View.INVISIBLE);                                    
						fd_msgList.get(curIndex).setError_type(View.INVISIBLE);	
						holder.error.setVisibility(fd_msgList.get(position).getRight_type());                                    
						holder.right.setVisibility(fd_msgList.get(position).getError_type());
						notifyDataSetChanged();
					}
		        	
		        });

		return convertView;
	}
	


	
	Handler handler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case RIGHT_CONST:
				//study_list
			    break;
			case ERROR_CONST:
				
				break;
			}
		};
	};


    private static AsyncHttpClient client = new AsyncHttpClient();
    private String curNum = "10086";
	private SharePreferenceUtil mSpUtil = HSApplication.getInstance().getSpUtil();
	/**
	 * 接受请求操作
	 */	
	public void AddRequest(){
    	RequestParams params = new RequestParams();
        String fromMobile =HSApplication.sp.getString("mobile","");
        String toMobile = fd_msgList.get(curIndex).getMobile();
        L.Debug("AddRequest fromMobile", fromMobile);
        L.Debug("AddRequest toMobile", toMobile);
		params.put("type", "2");//接受请求
		params.put("fromMobile",fromMobile );//mSpUtil.getMobile()
		params.put("toMobile", toMobile); //curNum 
		//		push onMessage: ={"response":"friendmsg","friendmsg":{"type":"2","friend":{"id":1,"mobile":"13166380861",
		//			"username":"测试者","headpic1":"1","token":"1111256221913402299","tokenType":1}}}
		client.post(NetContact.LOAD_FRIEND_REQUEST_URL,
				params, new JsonHttpResponseHandler() {
	
					
			    @Override
			    public void onSuccess(JSONObject response) {
			        System.out.println(response.toString());
			        try {
						String  type = response.getString("response");
				        if(type.equals("true")){
				        	
				        	curItem = fd_msgList.get(curIndex);			        	
							String id = curItem.getUserId(); //curItem.getUserId()
							String mobile = curItem.getMobile();//curItem.getMobile()
							String username = curItem.getNick();//curItem.getNick()
							L.Debug("LOAD_FRIEND_REQUEST_URL id", id);
							L.Debug("LOAD_FRIEND_REQUEST_URL mobile", mobile);
							L.Debug("LOAD_FRIEND_REQUEST_URL username", username);
							User user = new User();
							user.setTelNum(mobile);
							user.setNick(username);
							user.setId(id);
							boolean isAdd = true;
							Item08View.study_list.add(user);
							
							if(Item08View.adapter!=null)
							Item08View.adapter.notifyDataSetChanged();
							
							//过滤好友列表添加重复的人
					//							for(int i=0;i<fd_msgList.size();i++){
					//								if(id.equals(fd_msgList.get(i).getUserId())){
					//									isAdd = false;
					//									break;
					//											
					//								}
					//							}
					//							if(isAdd==true){
					//
					//							}
		        	
				        }
				        else{
				        	Util.toast(mContext, "没有此用户");
				        }
					} catch (JSONException e) {
						L.Debug("FdListViewAdapter 接受请求 JSONException", e.getMessage());
						e.printStackTrace();
					}

			    }	
			    
				//					public void onSuccess2(JSONObject response) {
				//						JSONArray jsonArray;
				//						try {
				//							L.Debug("接受请求  response", response.toString());
				//	
				//							String MeContent = new JSONObject(response.toString()).getString("friendmsg");
				//							JSONObject json = new JSONObject(MeContent);
				//							JSONObject friend_json = json.getJSONObject("friend");
				//							String id = friend_json.getString("id");
				//							String mobile = friend_json.getString("mobile");
				//							String username = friend_json.getString("username");
				//							User user = new User();
				//							user.setTelNum(id);
				//							user.setNick(mobile);
				//							user.setId(username);
				//							Item08View.study_list.add(user);
				//
				//						} catch (JSONException e) {
				//							e.printStackTrace();
				//							L.Debug("接受请求 JSONException", e.getMessage());
				//						}
				//								
				//					}

				});		
	}
	
	/**
	 * 添加学友
	 * @param message
	 */
	//	public void Add_Study_List(String message){
	//
	//			User user = new User();
	//		
	//		user.setTelNum("");
	//		user.setNick("");
	//		user.setId("");
	//		Item08View.study_list.add(user);
	//	}
	
}

class Holder_fd{
	public ImageView head;
	public TextView text;
	public Button right;
	public Button error;
}